package org.jeecg.modules.basic.basicSkuInfo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.constant.WarehouseConstant;
import org.jeecg.modules.basic.basicSkuInfo.entity.BasicSkuInfo;
import org.jeecg.modules.basic.basicSkuInfo.service.IBasicSkuInfoService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 基础数据-品番信息
 * @Author: jeecg-boot
 * @Date: 2024-11-29
 * @Version: V1.0
 */
@Api(tags = "基础数据-品番信息")
@RestController
@RequestMapping("/basicSkuInfo/basicSkuInfo")
@Slf4j
public class BasicSkuInfoController extends JeecgController<BasicSkuInfo, IBasicSkuInfoService> {
    @Autowired
    private IBasicSkuInfoService basicSkuInfoService;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param basicSkuInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "基础数据-品番信息-分页列表查询")
    @ApiOperation(value = "基础数据-品番信息-分页列表查询", notes = "基础数据-品番信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(BasicSkuInfo basicSkuInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<BasicSkuInfo> queryWrapper = QueryGenerator.initQueryWrapper(basicSkuInfo, req.getParameterMap());
        Page<BasicSkuInfo> page = new Page<BasicSkuInfo>(pageNo, pageSize);
        IPage<BasicSkuInfo> pageList = basicSkuInfoService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param basicSkuInfo
     * @return
     */
    @AutoLog(value = "基础数据-品番信息-添加")
    @ApiOperation(value = "基础数据-品番信息-添加", notes = "基础数据-品番信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody BasicSkuInfo basicSkuInfo) {
        basicSkuInfo = this.checkColumns(basicSkuInfo);
        basicSkuInfoService.save(basicSkuInfo);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param basicSkuInfo
     * @return
     */
    @AutoLog(value = "基础数据-品番信息-编辑")
    @ApiOperation(value = "基础数据-品番信息-编辑", notes = "基础数据-品番信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody BasicSkuInfo basicSkuInfo) {
        basicSkuInfo = this.checkColumns(basicSkuInfo);
        basicSkuInfoService.updateById(basicSkuInfo);
        return Result.OK("编辑成功!");
    }

    private BasicSkuInfo checkColumns(BasicSkuInfo basicSkuInfo) {
        Assert.notNull(basicSkuInfo.getSkuType(), "缺少必要参数品番类型！");
        Assert.isTrue(StringUtils.isNotBlank(basicSkuInfo.getSkuCode()), "请填写品番编码！");

        QueryWrapper<BasicSkuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(null != basicSkuInfo.getId(), "id", basicSkuInfo.getId());
        queryWrapper.eq("sku_type", basicSkuInfo.getSkuType());
        queryWrapper.eq("sku_code", basicSkuInfo.getSkuCode());

        if (WarehouseConstant.SkuTypeEnum.PT.getCode().equals(basicSkuInfo.getSkuType())) {
            Assert.isTrue(StringUtils.isNotBlank(basicSkuInfo.getCustomerName()), "请填写客户名称！");
            Assert.isTrue(StringUtils.isNotBlank(basicSkuInfo.getCustomerSku()), "请填写客户品番！");

            queryWrapper.eq("customer_name", basicSkuInfo.getCustomerName());
            queryWrapper.eq("customer_sku", basicSkuInfo.getCustomerSku());
            int repeatCount = basicSkuInfoService.count(queryWrapper);
            Assert.isTrue(repeatCount == 0, "系统中已存在相同的品番编码、客户名称、客户品番，无需重复录入！");
        } else if (WarehouseConstant.SkuTypeEnum.SF.getCode().equals(basicSkuInfo.getSkuType())) {
            basicSkuInfo.setOutLength(null == basicSkuInfo.getEnterLength() ? null : basicSkuInfo.getEnterLength());
            basicSkuInfo.setOutWidth(null == basicSkuInfo.getEnterWidth() ? null : basicSkuInfo.getEnterWidth());
            basicSkuInfo.setOutHigh(null == basicSkuInfo.getEnterHigh() ? null : basicSkuInfo.getEnterHigh());
            basicSkuInfo.setOutVolume(null == basicSkuInfo.getEnterVolume() ? null : basicSkuInfo.getEnterVolume());
            basicSkuInfo.setOutSpecification(null == basicSkuInfo.getEnterSpecification() ? null : basicSkuInfo.getEnterSpecification());

            int repeatCount = basicSkuInfoService.count(queryWrapper);
            Assert.isTrue(repeatCount == 0, "系统中已存在相同的品番编码，无需重复录入！");
        }

        return basicSkuInfo;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "基础数据-品番信息-通过id删除")
    @ApiOperation(value = "基础数据-品番信息-通过id删除", notes = "基础数据-品番信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        basicSkuInfoService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "基础数据-品番信息-批量删除")
    @ApiOperation(value = "基础数据-品番信息-批量删除", notes = "基础数据-品番信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.basicSkuInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "基础数据-品番信息-通过id查询")
    @ApiOperation(value = "基础数据-品番信息-通过id查询", notes = "基础数据-品番信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        BasicSkuInfo basicSkuInfo = basicSkuInfoService.getById(id);
        if (basicSkuInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(basicSkuInfo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param basicSkuInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasicSkuInfo basicSkuInfo) {
        // Step.1 组装查询条件
        QueryWrapper<BasicSkuInfo> queryWrapper = QueryGenerator.initQueryWrapper(basicSkuInfo, request.getParameterMap());
        queryWrapper.eq("sku_type", basicSkuInfo.getSkuType());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<BasicSkuInfo> pageList = basicSkuInfoService.list(queryWrapper);
        List<BasicSkuInfo> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        String title = basicSkuInfo.getSkuType() == 1 ? "PT品品番" : "市贩品品番";
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, BasicSkuInfo.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 获取对象ID
     *
     * @return
     */
    private String getId(BasicSkuInfo item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BasicSkuInfo.class);
    }

}
